package com.jiangyao.config;

import com.jiangyao.common.aop.CacheAop;
import com.jiangyao.common.constants.CacheConstants;
import com.jiangyao.common.utils.WechatUtils;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * WebMvc配置
 *
 * @author: yangyongchuan
 * @create: 2020年04月30日 10:06
 */
@SpringBootConfiguration
public class WebMvcConfig implements WebMvcConfigurer {

	private CorsConfiguration buildConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.addAllowedOrigin("*");
		corsConfiguration.addAllowedHeader("*");
		corsConfiguration.addAllowedMethod("*");
		corsConfiguration.setAllowCredentials(Boolean.valueOf(true));
		return corsConfiguration;
	}

	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig());
		return new CorsFilter(source);
	}


	/**
	 * 注册微信工具类
	 *
	 * @return 微信工具类
	 */
	@Bean
	public WechatUtils wechatUtils() {
		return new WechatUtils();
	}

	/**
	 * 注册缓存aop
	 *
	 * @return 缓存aop
	 */
	@Bean
	public CacheAop cacheAop() {
		return new CacheAop(CacheConstants.CACHE_KEY_AOP_API_PREFIX);
	}


	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/swagger-ui").setViewName("forward:/swagger-ui/index.html");
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/swagger-ui/**")
				.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
				.resourceChain(false);
	}

}
